<?php
declare (strict_types=1);

namespace ffhome\frame\controller;

abstract class SimpleCommonController extends QueryController
{
    public function index()
    {
        $param = request()->param();
        $page = isset($param['page']) && !empty($param['page']) ? intval($param['page']) : 1;
        $limit = isset($param['limit']) && !empty($param['limit']) ? intval($param['limit']) : $this->defaultPageSize;

        $where = $this->generateIndexWhere($param, $page, $limit);
        $ret = [];
        if ($page == 1) {
            $ret['total_count'] = $this->getSearchModel($where)->count();
            $ret['total_page'] = ceil($ret['total_count'] / $limit);
            if ($ret['total_page'] > 0) {
                $ret['list'] = $this->getList($where, $page, $limit);
            } else {
                $ret['list'] = [];
            }
        } else {
            $ret['list'] = $this->getList($where, $page, $limit);
        }
        $this->json_result($ret);
    }

    protected function generateIndexWhere($param, $page, $limit)
    {
        return $this->buildWhere($param);
    }

    protected function getList($where, $page, $limit)
    {
        return $this->getSearchModel($where)
            ->page($page, $limit)
            ->field($this->getSearchFields())
            ->order($this->getSearchSort())
            ->select()->toArray();
    }

    public function detail(int $id)
    {
        $row = $this->getModelInfo($id);
        $this->onAfterDetail($id, $row);
        $this->json_result($row);
    }

    protected function onAfterDetail(int $id, array &$row)
    {
    }
}